//
//  SalesPolicyViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/7/11.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "SalesPolicyViewController.h"

#import "ComboBoxView.h"
//销售详情
#import "DetailSaleViewController.h"

#import "SearchResultsViewController.h"

#import "PolicyModel.h"

@interface SalesPolicyViewController ()<UITableViewDataSource,UITableViewDelegate,sendSelectecdIndexDelegate>
{
    ComboBoxView  *_comboBox;
    /**下拉框选项*/
    NSInteger _comboxSelectedIndex;
    NSInteger _classid;
    
     BOOL _needRefresh;
}

@property (nonatomic, strong) UITableView    * salesPolicyTableView;

@property (nonatomic, strong) NSMutableArray * dataSourceArry;
@property (nonatomic, strong) NSMutableArray * resultArry;
/**分页*/
@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation SalesPolicyViewController


- (instancetype)init {
    self = [super init];
    if (self) {
        
        _dataSourceArry = [NSMutableArray array];
        _resultArry = [NSMutableArray array];
        _pageIndex = 1;
        _classid = 3;
        _comboxSelectedIndex = 0;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self requestForData];
    [self creatUI];
    [self creatComboBoxAndSearchButton];
}


#pragma mark ------网络请求数据-----------------

- (void)requestForData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSDictionary *parameters = @{@"classid":[NSString stringWithFormat:@"%ld",(long)_classid],
                                 @"pagesize":@"20",
                                 @"pageindex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],
                                 @"time":[NSString stringWithFormat:@"%ld",(long)_comboxSelectedIndex]};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.article.list" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"营销政策的dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            if (_needRefresh) {
                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
                [_dataSourceArry removeAllObjects];
            }
            
            
            
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                PolicyModel *policyModel = [[PolicyModel alloc]init];
                [policyModel setValuesForKeysWithDictionary:dataDic];
                [_dataSourceArry addObject:policyModel];
                [_resultArry addObject:policyModel.name];
            }
            
            [_salesPolicyTableView reloadData];
            
            if ([dictionary[@"total"] integerValue] < 20) {
                
                //[_personalTableView.footer resetNoMoreData];
                
                [_salesPolicyTableView.footer endRefreshing];
                [_salesPolicyTableView.header endRefreshing];
                [_salesPolicyTableView.footer noticeNoMoreData];
                return ;
            }
            
            
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        [_salesPolicyTableView.footer endRefreshing];
        [_salesPolicyTableView.header endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        [_salesPolicyTableView.footer endRefreshing];
        [_salesPolicyTableView.header endRefreshing];
    }];
    
}


- (void)creatUI {
    //主界面数据展示
    _salesPolicyTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    
    
    //_salesPolicyTableView.backgroundColor = [UIColor yellowColor];
    _salesPolicyTableView.dataSource=self;
    _salesPolicyTableView.delegate=self;
    
    //_salesPolicyTableView.tableHeaderView = _searchBar;
    _salesPolicyTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    _salesPolicyTableView.backgroundColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0];
    
   // [self.view addSubview:_searchBar];
    [self.view addSubview:_salesPolicyTableView];
    
    
    __weak typeof(self) weakSelf = self;
    [_salesPolicyTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [_salesPolicyTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];

    
    
}

- (void)headerRefresh{
    _needRefresh = YES;
    _pageIndex = 1;
    [self requestForData];
}
- (void)footerRefresh{
    _needRefresh = NO;
    _pageIndex ++;
    [self requestForData];
}

- (void)creatComboBoxAndSearchButton {
    NSArray *comboBoxDatasource = [[NSArray alloc] initWithObjects:@"全部", @"本周", @"本月", @"最近三月", @"最近半年", @"最近一年", nil];
    
    _comboBox = [[ComboBoxView alloc] initWithFrame:CGRectMake(SCREEN_W/2, 0, SCREEN_W/2, 180)];
    _comboBox.comboBoxDatasource = comboBoxDatasource;
    _comboBox.backgroundColor = [UIColor clearColor];
    _comboBox.delegate = self;
    [_comboBox setContent:[comboBoxDatasource objectAtIndex:0]];
    //[_comboBox.com];
    [self.view addSubview:_comboBox];
    
    
//    搜索按钮
    UIButton *searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W/2, 37)];
    
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    //searchButton.font = [UIFont fontWithName:@"Arial" size:12.0f];
    searchButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
    searchButton.titleLabel.textAlignment = NSTextAlignmentLeft;//设置title的字体居中
    [searchButton setBackgroundImage:[UIImage imageNamed:@"bankuang_"] forState:UIControlStateNormal];
    [searchButton setImage:[UIImage imageNamed:@"sousuo_"] forState:UIControlStateNormal];
    [searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//设置title在一般情况下为色字体
    [searchButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];//设置title在button被选中情况下为灰色字体
    
    //searchButton.titleEdgeInsets = UIEdgeInsetsMake(0, -55, 0, 0);
    searchButton.imageEdgeInsets = UIEdgeInsetsMake(0,-30,0,0);
    
    
    [searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:searchButton];
    
}
#pragma mark-sendSelectecdIndexDelegate
- (void)sendSelectedIndex:(NSInteger)selectedIndex {
    [_dataSourceArry removeAllObjects];
    _pageIndex = 1;
    _comboxSelectedIndex = selectedIndex;
    [self requestForData];
}

#pragma mark - ---------------------------Search Delegate----------------------------

- (void)searchButtonClick {
    
    SearchResultsViewController *searchResult = [[SearchResultsViewController alloc]init];

    searchResult.dataSourceArry = _dataSourceArry;
    searchResult.nameArray = _resultArry;
    [self.navigationController pushViewController:searchResult animated:NO];

}


#pragma mark- ------------------------UITableView 代理实现--------------------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

//设置rows的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [_dataSourceArry count];

}


//Cell的相关设置
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellName=@"cell";
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if(cell==nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
    }

    PolicyModel *policyModel = _dataSourceArry[indexPath.row];
    
    policyModel.name = [policyModel.name stringByReplacingOccurrencesOfString:@"+" withString:@""];
    cell.textLabel.text=policyModel.name;
    policyModel.addtime =[policyModel.addtime stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    cell.detailTextLabel.text = policyModel.addtime;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
    
    DetailSaleViewController *detailSaleViewController = [[DetailSaleViewController alloc] init];
    PolicyModel *policyModel = _dataSourceArry[indexPath.row];
    detailSaleViewController.title = @"政策详情";
    detailSaleViewController.policyTitle = [policyModel.name stringByReplacingOccurrencesOfString:@"+" withString:@""];
    detailSaleViewController.article_id = policyModel.aid;
    [self.navigationController pushViewController:detailSaleViewController animated:NO];
    //    [self.navigationControllerpopToRootViewControllerAnimated:YES];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}



@end
